import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { DbService } from "@/db/db.service";
import { UserEntity } from "@/db/entitys/user.entity";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    private readonly dbService: DbService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get("JWT_SECRET"),
    });
  }

  async validate(payload: { id: number }): Promise<UserEntity> {
    const user = await this.dbService.userRepository.findOneBy({
      id: payload.id,
    });
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
